package com.eva.databuilder.builders.cms;

import cn.hutool.core.util.ObjectUtil;
import com.eva.cms.biz.category.CmsCategoryBiz;
import com.eva.cms.biz.category.vo.CmsCategoryNodeVO;
import com.eva.databuilder.bo.TemplateDataParameters;
import com.eva.dao.cms.model.CmsTemplate;
import com.eva.framework.cache.CacheProxy;
import com.eva.framework.config.AppConfig;
import com.eva.service.cms.CmsTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 构建子栏目树数据
 */
@Slf4j
@Component
public class SubCategoryTreeBuilder extends BaseCategoryTreeBuilder {

    private final static String PARAMETER_PARENT_CATEGORY_UID = "parentCategoryUid";

    @Resource
    private CmsCategoryBiz cmsCategoryBiz;

    @Resource
    private CmsTemplateService cmsTemplateService;

    @Resource
    private CacheProxy<String, List<CmsCategoryNodeVO>> cacheProxy;

    @Resource
    private AppConfig appConfig;

    @Override
    public List<CmsCategoryNodeVO> build(TemplateDataParameters parameters) {
        // 组装缓存键
        String cacheKey = "category:" +
                parameters.getString(PARAMETER_PARENT_CATEGORY_UID, null) + ":children";
        // 优先从缓存中获取
        List<CmsCategoryNodeVO> subCategories = cacheProxy.get(cacheKey);
        if (subCategories != null) {
            return subCategories;
        }
        // 如果缓存中没有，则查询数据库
        subCategories = cmsCategoryBiz.findSubTree(
                parameters.getString(PARAMETER_PARENT_CATEGORY_UID, null),
                Boolean.FALSE);
        // 获取栏目模板ID集合
        Set<Integer> templateIds = new HashSet<>();
        this.getTemplateIds(subCategories, templateIds);
        // 根据模板ID进行分组
        Map<Integer, CmsTemplate> cmsTemplateMap = cmsTemplateService.findByIds(templateIds)
                .stream()
                .collect(Collectors.toMap(CmsTemplate::getId, cmsTemplate -> cmsTemplate));
        // 补充常规栏目的uri
        this.paddingCategoryUri(subCategories, cmsTemplateMap);
        // 编译栏目的uri
        this.compileCategoryUri(subCategories, parameters);
        // 写入到缓存中
        if (ObjectUtil.isNotEmpty(subCategories)) {
            cacheProxy.put(cacheKey, subCategories, appConfig.getTemplateDataCacheExpire());;
        }
        return subCategories;
    }
}
